#!/bin/bash

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

. /etc/sysconfig/cloudstack-usage

start() {
    if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
        echo "$PROGNAME apparently already running"
        exit 0
    fi

    if hostname --fqdn >/dev/null 2>&1 ; then
        true
    else
        echo "The host name does not resolve properly to an IP address. Cannot start $PROGNAME"
        exit 1
    fi

    echo -n "Starting $PROGNAME" "$SHORTNAME"

    if /usr/bin/jsvc -pidfile $PIDFILE $DAEMON -home "$JAVA_HOME" -cp "$CLASSPATH" -pidfile "$PIDFILE" -user "$USER" \
      -errfile $LOGDIR/cloudstack-usage.err -outfile $LOGDIR/cloudstack-usage.out -Dpid=$$ $CLASS
        RETVAL=$?
    then
        rc=0
        sleep 1
        if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
            rc=1
        fi
    else
        rc=1
    fi

    if [ $rc -ne 0 ]; then
        echo > "$PIDFILE"
        exit 1
    fi
}

stop() {
    echo -n "Stopping $PROGNAME" "$SHORTNAME"
    if [ -e $PIDFILE ] ; then
        kill $(<$PIDFILE) > /dev/null 2>&1
        echo > $PIDFILE
    else
        echo Unable to stop $SHORTNAME, no pid file
        echo > $PIDFILE
        exit 1
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status -p $PIDFILE $SHORTNAME
        RETVAL=$?
        ;;
    restart | force-reload)
        stop
        sleep 3
        start
        ;;
    *)
    echo "Usage: $0 {start|stop|restart|force-reload|status}"
    RETVAL=3
esac

exit $RETVAL

